package com.jstyle.jclifexd.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.jstyle.countrylibrary.CountryPage;
import com.jstyle.jclifexd.NetWork.NetWorkException;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.BindDeviceActivity;
import com.jstyle.jclifexd.activity.FindPasswordActivity;
import com.jstyle.jclifexd.activity.HeartTipsActivity;
import com.jstyle.jclifexd.activity.MainActivity;
import com.jstyle.jclifexd.activity.ProvicyAboutActivity;
import com.jstyle.jclifexd.activity.ProvicyActivity;
import com.jstyle.jclifexd.activity.RegisterActivity;
import com.jstyle.jclifexd.activity.UserInfoSettingActivity;
import com.jstyle.jclifexd.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.ActionData;
import com.jstyle.jclifexd.model.BindDeviceInfo;
import com.jstyle.jclifexd.model.NetResultData;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.model.UserInfoQuery;
import com.jstyle.jclifexd.model.gomore.GomoreInfo;
import com.jstyle.jclifexd.utils.ImageUtils;
import com.jstyle.jclifexd.utils.NetWorkConast;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.SHA1;
import com.jstyle.jclifexd.utils.SchedulersTransformer;
import com.jstyle.jclifexd.utils.ShareTools;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.EditTextWithDelete;
import com.mob.tools.FakeActivity;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.google.GooglePlus;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.twitter.Twitter;
import cn.sharesdk.wechat.friends.Wechat;
import cn.smssdk.SMSSDK;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


/**
 * 登录
 */
public class LoginFragment extends BaseFragment implements PlatformActionListener {
    private static final String TAG = "LoginFragment";

    @BindView(R.id.et_login_phonenumber)
    EditTextWithDelete etLoginPhonenumber;
    @BindView(R.id.et_login_password)
    EditTextWithDelete etLoginPassword;
    @BindView(R.id.tv_login_forgetpassword)
    TextView tvLoginForgetpassword;
    @BindView(R.id.bt_login_login)
    Button btLoginLogin;


    ShareTools shareTools;
    String token;
    @BindView(R.id.tv_to_register)
    TextView tvToRegister;
    @BindView(R.id.bt_login_type1)
    ImageView bt_login_type1;
    @BindView(R.id.bt_login_type2)
    ImageView bt_login_type2;
    @BindView(R.id.bt_login_type3)
    ImageView bt_login_type3;
    @BindView(R.id.RadioButton_sign_phone)
    RadioButton RadioButtonSignPhone;
    @BindView(R.id.RadioButton_sign_email)
    RadioButton RadioButtonSignEmail;
    @BindView(R.id.RadioGroup_loginAccount)
    RadioGroup RadioGroupLoginAccount;
    @BindView(R.id.checkbox_login)
    CheckBox checkboxLogin;


    //    @BindView(R.id.rb_login_phone)
//    RadioButton rbLoginPhone;
//    @BindView(R.id.rb_login_email)
//    RadioButton rbLoginEmail;
//    @BindView(R.id.RadioGroup_loginAccount)
//    RadioGroup RadioGroupLoginAccount;
    private String countryCode = "001-";

    @BindView(R.id.bt_login_getCountryCode)
    Button btLoginGetCountryCode;
    private String language = "zh";
    private Disposable subscription;
    boolean isagree = false;//中文下需要用到权限同意
    private GoogleSignInAccount account;


    private void saveUserInfo(String id) {
        uid = id;
        String phone = etLoginPhonenumber.getText().toString();
        String psd = etLoginPassword.getText().toString();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(id);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(id);
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);
            UserInfoDaoManager.insertUser(userInfo);
        } else {
            userInfo.setUserId(id);
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);
            UserInfoDaoManager.updateUser(userInfo);
        }
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_REMIND_PSD, checkboxLogin.isChecked());
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_account_type, isPhoneAccount);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_AUTH_USERID, "");
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PHONE, phone);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PSD, psd);

    }


    boolean isPhoneAccount = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, null);
        ButterKnife.bind(this, view);
        initView();
        // shareTools = new ShareTools(this);
        //   shareTools.setShareListener(this);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    private void initView() {
        //如果手机系统为中文设置第三方为，微信，qq,微博，其他语言facebook,twitter,google+
        if (Utils.isZh(getActivity())) {
            bt_login_type1.setImageDrawable(getResources().getDrawable(R.drawable.login_wechat));
            bt_login_type2.setImageDrawable(getResources().getDrawable(R.drawable.login_qq));
            bt_login_type3.setImageDrawable(getResources().getDrawable(R.drawable.login_weibo));
        } else {
            bt_login_type1.setImageDrawable(getResources().getDrawable(R.drawable.login_facebook));
            bt_login_type2.setImageDrawable(getResources().getDrawable(R.drawable.login_twitter));
            bt_login_type3.setImageDrawable(getResources().getDrawable(R.drawable.login_google));
        }
        tvToRegister.setText(Html.fromHtml(getString(R.string.register_link)));
        Locale locale = getResources().getConfiguration().locale;
        language = locale.getLanguage();
        //llLogin2.setVisibility(language.equals("zh") ? View.GONE : View.VISIBLE);
        //llLogin1.setVisibility(language.equals("zh") ? View.VISIBLE : View.GONE);
        boolean isRemind = SharedPreferenceUtils.getSpBoolean(SharedPreferenceUtils.KEY_REMIND_PSD);

        isPhoneAccount = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_account_type,
                "zh".equals(language));

        if (isPhoneAccount) {
            RadioButtonSignPhone.setChecked(true);
        } else {
            RadioButtonSignEmail.setChecked(true);
        }
        switchAccountType(isPhoneAccount);

        showUserInfo();
        checkboxLogin.setChecked(isRemind);


        RadioGroupLoginAccount.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.RadioButton_sign_phone:
                        isPhoneAccount = true;
                        break;
                    case R.id.RadioButton_sign_email:
                        isPhoneAccount = false;
                        break;
                }
                switchAccountType(isPhoneAccount);
            }
        });
        Utils.setEditTextInhibitInputSpace(etLoginPassword);
        Utils.setEditTextInhibitInputSpace(etLoginPhonenumber);
        subscription = RxBus.getInstance().toObservable(ActionData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ActionData>() {
            @Override
            public void accept(ActionData data) throws Exception {
                String action = data.getAction();
                if (ActionData.FinishSignIn.equals(action)) {
                    showUserInfo();
                    login();
                }
            }
        });




    }

    private void changeUserAccount() {

    }

    private void showUserInfo() {

        countryCode = SharedPreferenceUtils.getString(SharedPreferenceUtils.KEY_countryCode, getString(R.string.DefaultCountryCode));
        btLoginGetCountryCode.setText("+" + countryCode.split("-")[0].replace("0", ""));

        //RadioGroupLoginAccount.check(isPhoneAccount?R.id.rb_login_phone:R.id.rb_login_email);
        String phone = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_PHONE);
        boolean isReminder = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_REMIND_PSD, false);
        if (!isReminder) return;
        String psd = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_PSD);
        if (!TextUtils.isEmpty(phone)) etLoginPhonenumber.setText(phone);
        if (!TextUtils.isEmpty(psd)) etLoginPassword.setText(psd);
    }


    @OnClick({R.id.tv_to_register, R.id.bt_login_getCountryCode, R.id.tv_login_forgetpassword, R.id.bt_login_login, R.id.bt_login_type1, R.id.bt_login_type2, R.id.bt_login_type3
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_login_type1:
                thirdLogin(Wechat.NAME, Facebook.NAME);
                //WeinxiandFecebokLOgin();
                break;
            case R.id.bt_login_type2:
                thirdLogin(QQ.NAME, Twitter.NAME);
                // QQandTwtterLogin();
                break;
            case R.id.bt_login_type3:
                thirdLogin(SinaWeibo.NAME, GooglePlus.NAME);
                //WeiboandGoogleLogin();
                break;
            case R.id.tv_to_register:
                startActivity(RegisterActivity.class);
                break;
            case R.id.tv_login_forgetpassword:
                startActivity(FindPasswordActivity.class);
                break;
            case R.id.bt_login_login:
                login();
                break;
            case R.id.bt_login_getCountryCode:
                getCountryCode();
                break;
        }
    }

    //    private void WeiboandGoogleLogin() {
//        if (Utils.isZh(getActivity())) {
//            if (checkbox_service.isChecked()) {
//                ThirdpartyLongin(SinaWeibo.NAME);//微博
//            } else {
//                showToast("请同意协议");
//            }
//        } else {
//            ThirdpartyLongin(GooglePlus.NAME);
//        }
//
//
//    }
    private void thirdLogin(String zhName, String otherName) {
        if (otherName.equals(GooglePlus.NAME)) {//google调用原生api
            signIn();
        } else {
            ThirdpartyLongin(otherName); //
        }

    }

    private int GOOGLE_SIGN_IN = 122;

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == GOOGLE_SIGN_IN) {
                //Subscribe();
                account = GoogleSignIn.getLastSignedInAccount(getContext());
                if (account == null) {
                    return;
                }
                String name = account.getDisplayName();
                String iconUrl = account.getPhotoUrl() == null ? "" : account.getPhotoUrl().toString();
                String openId = account.getId();
                FindUserInfo(openId, "Google", iconUrl, name);
            }
        }
    }

    private void signIn() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
        GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(getContext(), gso);
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
    }
//    private void QQandTwtterLogin() {
//        if (Utils.isZh(getActivity())) {
//            if (checkbox_service.isChecked()) {
//                ThirdpartyLongin(QQ.NAME); //qq
//            } else {
//                showToast("请同意协议");
//            }
//        } else {
//            ThirdpartyLongin(Twitter.NAME); //
//        }
//
//    }

//    private void WeinxiandFecebokLOgin() {
//        if (Utils.isZh(getActivity())) {
//            if (checkbox_service.isChecked()) {
//                ThirdpartyLongin( Wechat.NAME );
//            } else {
//                showToast("请同意协议");
//            }
//        } else {
//            ThirdpartyLongin( Facebook.NAME);
//        }
//    }

    private void getCountryCode() {
        CountryPage phone = new CountryPage();
        phone.setCountryId("1");
        Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "SourceHanSansCN-Regular.ttf");
        phone.setTypeFace(typeface);
        phone.showForResult(getActivity(), (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                if (null != data && null != data.get("id")) {
                    String currentId = (String) data.get("id");
                    int result = (int) data.get("result");
                    if (result == CountryPage.Result_OK) {
                        String[] res = SMSSDK.getCountry(currentId);
                        btLoginGetCountryCode.setText("+" + res[1]);
                        countryCode = "00" + res[1] + "-";
                    }
                }

            }
        });

    }

    private void login() {
        if (!NetWorkUtil.isNetworkConnected(getContext())) {
            showToast(getResources().getString(R.string.Network_not_availa));
            return;
        }
        Log.i(TAG, "login: " + language);
        Locale locale = getResources().getConfiguration().locale;
        Log.i(TAG, "login: " + locale.getLanguage());
        String account = etLoginPhonenumber.getText().toString();
        String password = etLoginPassword.getText().toString();
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(account)) {
            showToast(getString(R.string.login_input_all));
            return;
        }

        Map<String, Object> map = new HashMap<>();

        if (isPhoneAccount) {
            map.put(NetWorkConast.KEY_PHONE, countryCode + account);
        } else {
            map.put(NetWorkConast.KEY_userEmail, account);
        }
        map.put(NetWorkConast.KEY_userpwd, password.length() == 32 ? password : SHA1.md5Encoder(password));
        NetWorkUtil.addSHA1(map);
        showProgressDialog(getString(R.string.login_logining));
        NetWorkUtil.getInstance()
                .getJstyleApi()
                .login(map)
                .flatMap(new Function<NetResultData<String>, ObservableSource<NetResultData<UserInfoQuery>>>() {
                    @Override
                    public ObservableSource<NetResultData<UserInfoQuery>> apply(NetResultData<String> netResultData) throws Exception {
                        int msgCode = netResultData.getMsgCode();
                        String msg = NetWorkConast.getResult(msgCode, getContext());
                        if (msgCode == NetResultData.Success_Code) {
                            // saveUserInfo(netResultData.getData());
                            return NetWorkUtil.getInstance()
                                    .getJstyleApi()
                                    .getUserInfo(netResultData.getData());
                        } else {
                            throw new NetWorkException(msg);
                        }
                    }
                })
                .compose(SchedulersTransformer.<NetResultData<UserInfoQuery>>io2MainObservable())
                .subscribe(new Observer<NetResultData<UserInfoQuery>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NetResultData<UserInfoQuery> value) {

                        finishLogin(value);

                    }

                    @Override
                    public void onError(Throwable e) {
                        disMissProgressDialog();
                        String msg = e.getMessage();
                        if (e instanceof ConnectException) {
                            msg = getString(R.string.Network_not_availa);
                        }
                        showToast(msg);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * @param value
     * @param name
     * @param iconUrl
     */
    private void finishThirdLogin(NetResultData<UserInfoQuery> value, String name, String iconUrl) {
        String avatar = value.getData().getAvatar();
        String nikeName = value.getData().getNikeName();
        if (TextUtils.isEmpty(nikeName) && !TextUtils.isEmpty(name))
            value.getData().setNikeName(name);
        if (TextUtils.isEmpty(avatar) && !TextUtils.isEmpty(iconUrl))
            value.getData().setAvatar(iconUrl);
        finishLogin(value);
    }

    String uid;


    private void finishLogin(NetResultData<UserInfoQuery> value) {
        disMissProgressDialog();
        int msgCode = value.getMsgCode();

        String msg = NetWorkConast.getResult(msgCode, getContext());
        if (msgCode == NetResultData.Success_Code) {
            SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, true);
            boolean isFirst = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_Is_First, true);
            if (value.getData() != null) {
                updateUserInfo(value.getData());
            }
            startActivity();
            getActivity().finish();
            return;
        } else if (msgCode == NetResultData.Failed_Code) {
            msg = getResources().getString(R.string.login_loginfailed);
        }
        showToast(msg);
    }

    private void startActivity() {
        boolean isFirst = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_Is_First, true);
        String uid = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_UID);
        Class next = null;
        if (isFirst) {
            next = BindDeviceActivity.class;
        } else {
            List<BindDeviceInfo> bindDeviceInfoList = BindDeviceInfoDaoManager.queryAllData();
            if (bindDeviceInfoList.size() != 0) {
                UserInfo userInfo = UserInfoDaoManager.getUserByUid(uid + "");
                //String iconPath = userInfo.getIconPath();
                next = TextUtils.isEmpty(userInfo.getIconPath()) ? UserInfoSettingActivity.class : MainActivity.class;
            } else {
                next = BindDeviceActivity.class;
            }
        }
        startActivity(next, SharedPreferenceUtils.KEY_From_Login, true);

    }

    private void updateUserInfo(UserInfoQuery data) {
        String uid = String.valueOf(data.getUid());
        CrashReport.setUserId(uid);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_UID, uid);
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(uid);
        String phone = etLoginPhonenumber.getText().toString();
        String psd = etLoginPassword.getText().toString();
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_REMIND_PSD, checkboxLogin.isChecked());
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_account_type, isPhoneAccount);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PHONE, phone);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PSD, psd);
        int age = 25;
        if (!TextUtils.isEmpty(data.getBirthday())) {
            String[] birthdayArray = data.getBirthday().split("-");
            int year = Integer.parseInt(birthdayArray[0]);
            Calendar calendar = Calendar.getInstance();
            int nowYear = calendar.get(Calendar.YEAR);
            age = nowYear - year;
        }
        int gender = 0;
        if (!TextUtils.isEmpty(data.getGender())) {
            gender = data.getGender().equals("male") ? 0 : 1;
        }
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);
            userInfo.setUserId(data.getUid() + "");
            userInfo.setAge(age);
            userInfo.setBirthday(data.getBirthday());
            userInfo.setHeight(data.getStature());
            if (!TextUtils.isEmpty(data.getAvatar())) userInfo.setIconPath(data.getAvatar());
            userInfo.setName(data.getNikeName());
            userInfo.setWeight(data.getWeight());
            userInfo.setGender(gender);
            UserInfoDaoManager.insertUser(userInfo);
        } else {
            userInfo.setPhone(phone);
            userInfo.setUserpwd(psd);
            userInfo.setUserId(data.getUid() + "");
            userInfo.setAge(age);
            userInfo.setBirthday(data.getBirthday());
            userInfo.setHeight(data.getStature());
            userInfo.setName(data.getNikeName());
            userInfo.setWeight(data.getWeight());
            if (!TextUtils.isEmpty(data.getAvatar())) userInfo.setIconPath(data.getAvatar());
            userInfo.setGender(gender);

            UserInfoDaoManager.updateUser(userInfo);
        }
        saveUserIcon(data.getAvatar());
    }

    @Override
    public void switchAccountType(boolean isPhoneAccount) {
        super.switchAccountType(isPhoneAccount);
        etLoginPassword.setText("");
        etLoginPhonenumber.setText("");
        etLoginPhonenumber.setHint(isPhoneAccount ? R.string.login_input_phone : R.string.login_input_email);
        btLoginGetCountryCode.setVisibility(isPhoneAccount ? View.VISIBLE : View.GONE);
    }

    //    @Override
//    public void ShareSuccess(String userName, String headUrl, String platName, String userId) {
//
//        getAuthUserInfo(userName, headUrl, platName, userId);
//        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_NICKNAME, userName);
//
//    }

    private void saveUserIcon(String headUrl) {
        if (TextUtils.isEmpty(headUrl)) return;
        NetWorkUtil.getInstance().getJstyleApi().downloadIcon(headUrl).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody value) {

                        try {
                            writeToDisk(value);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {


                    }
                });
    }

    private void writeToDisk(ResponseBody responseBody) throws IOException {
        File file = new File(ImageUtils.headPath);
        File fileIcon = new File(ImageUtils.headPath + ImageUtils.md5Encoder(NetWorkUtil.getUserId()));
        Log.i(TAG, "writeToDisk: " + ImageUtils.md5Encoder(NetWorkUtil.getUserId()));
        if (!file.exists()) {
            file.mkdirs();
        }
        if (fileIcon.exists() && fileIcon.length() == responseBody.contentLength()) {
            // finishLogin();
            return;
        }
        try {
            byte[] buffer = new byte[1024 * 8];
            int len;
            FileOutputStream out = new FileOutputStream(fileIcon);
            InputStream in = responseBody.byteStream();
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (FileNotFoundException E) {
            E.printStackTrace();
        }
        //  finishLogin();
    }


//    @Override
//    public void ShareFailed() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                showToast(getString(R.string.login_loginfailed));
//            }
//        });
//    }

//    @Override
//    public void shareCancel() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                showToast(getString(R.string.login_third_usercancel));
//            }
//        });
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unSubscribe(subscription);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    private void ThirdpartyLongin(final String name) {
        Platform platform = ShareSDK.getPlatform(name);
        platform.SSOSetting(false);
        if (TextUtils.isEmpty(name)) {
            return;
        }
        // if (platform.isClientValid()) {
        authorize(platform);
//        } else {
//            //未安装,请先安装
//            String packageName = "";
//            String info = "";
//            if (Wechat.NAME.equals(name)) {
//                packageName = "com.tencent.mm";
//                info = String.format(getString(R.string.Wechat_not_installed), "Wechat");
//            } else if (QQ.NAME.equals(name)) {
//                packageName = "com.tencent.mobileqq";
//                info = String.format(getString(R.string.Wechat_not_installed), "QQ");
//            } else if (SinaWeibo.NAME.equals(name)) {
//                packageName = "com.sina.weibo";
//                info = String.format(getString(R.string.Wechat_not_installed), "SinaWeibo");
//            } else if (Facebook.NAME.equals(name)) {
//                packageName = "com.facebook.katana";
//                info = String.format(getString(R.string.Wechat_not_installed), "Facebook");
//            } else if (GooglePlus.NAME.equals(name)) {
//                packageName = "com.twitter.android";
//                info = String.format(getString(R.string.Wechat_not_installed), "Google+");
//            } else if (Twitter.NAME.equals(name)) {
//                packageName = "com.google.android.apps.plus";
//                info = String.format(getString(R.string.Wechat_not_installed), "Twitter");
//            }
//
//            ShowDialog(packageName, info);
//
//        }

    }


    private void authorize(Platform plat) {
        if (plat == null) {
            return;
        }
        if (plat.isAuthValid()) {//如果已经授权了，清楚授权
            plat.SSOSetting(true);
            plat.removeAccount(true);
            ShareSDK.removeCookieOnAuthorize(true);
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(plat.getName().equals(Facebook.NAME));
        plat.showUser(null);//授权返回用户信息
    }


    /**
     * 第三方登录获取信息回调
     */
    @Override
    public void onComplete(final Platform platform, int i, final HashMap<String, Object> hashMap) {
        //qq , wechat, weibo, facebook, google+, twitter
        //这里获取到标识后其他的不用管了
        Log.i(TAG, platform + "********" + hashMap.toString());
        final PlatformDb platformDb = platform.getDb();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (Wechat.NAME.equals(platform.getName())) {
                    FindUserInfo(platformDb.getUserId(), "wechat", platformDb.getUserIcon(), platformDb.getUserName());
                } else if (QQ.NAME.equals(platform.getName())) {
                    String iconUrl = (String) hashMap.get("figureurl_qq_2");//100*100;
                    if (TextUtils.isEmpty(iconUrl)) {
                        iconUrl = (String) hashMap.get("figureurl_qq_1");//40*40;
                    }
                    FindUserInfo(platformDb.getUserId(), "qq", iconUrl, platformDb.getUserName());
                } else if (SinaWeibo.NAME.equals(platform.getName())) {
                    FindUserInfo(platformDb.getUserId(), "weibo", platformDb.getUserIcon(), platformDb.getUserName());
                } else if (Facebook.NAME.equals(platform.getName())) {
                    // showToast(hashMap.toString());

                    FindUserInfo(platformDb.getUserId(), platform.getName(), platformDb.getUserIcon(), platformDb.getUserName());
                } else if (Twitter.NAME.equals(platform.getName())) {
                    //showToast(hashMap.toString());
                    FindUserInfo(platformDb.getUserId(), platform.getName(), platformDb.getUserIcon(), platformDb.getUserName());

                } else if (GooglePlus.NAME.equals(platform.getName())) {
                    //  showToast(hashMap.toString());
                    FindUserInfo(platformDb.getUserId(), platform.getName(), platformDb.getUserIcon(), platformDb.getUserName());

                }
            }
        });


    }

    /**
     * 第三方登录错误回调
     */
    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Log.e(TAG, i + "********" + throwable.getMessage());
    }

    /**
     * 第三方登录取消
     */
    @Override
    public void onCancel(Platform platform, int i) {

    }

    public void FindUserInfo(String openID, String platName, final String iconUrl, final String userName) {
        Log.i(TAG, "FindUserInfo: " + openID + " " + iconUrl);
        if (TextUtils.isEmpty(openID) || TextUtils.isEmpty(platName)) {
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("openID", openID);
        map.put("platName", platName);
        NetWorkUtil.getInstance().getJstyleApi()
                .thirdinfo(map).flatMap(new Function<GomoreInfo, ObservableSource<NetResultData<UserInfoQuery>>>() {
            @Override
            public ObservableSource<NetResultData<UserInfoQuery>> apply(GomoreInfo netResultData) throws Exception {
                int msgCode = netResultData.getMsgCode();
                String msg = NetWorkConast.getResult(msgCode, getContext());
                if (msgCode == NetResultData.Success_Code) {
                    // saveUserInfo(netResultData.getData());
                    return NetWorkUtil.getInstance()
                            .getJstyleApi()
                            .getUserInfo(netResultData.getData());
                } else {
                    throw new NetWorkException(msg);
                }
            }
        }).compose(SchedulersTransformer.<NetResultData<UserInfoQuery>>io2MainObservable()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showProgressDialog(getString(R.string.wait));
            }
        }).subscribe(new Observer<NetResultData<UserInfoQuery>>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData<UserInfoQuery> userInfoQueryNetResultData) {
                finishThirdLogin(userInfoQueryNetResultData, userName, iconUrl);
                disMissProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
                disMissProgressDialog();
            }

            @Override
            public void onComplete() {

            }
        });


    }

    private void GetInfo(final String ID) {
        NetWorkUtil.getInstance().getJstyleApi().getUserInfo(ID).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<NetResultData<UserInfoQuery>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(NetResultData<UserInfoQuery> thirdinfo) {
                if (thirdinfo.getMsgCode() == 1) {
                    if (null != thirdinfo.getData()) {
                        //判断是否已经有信息了
                        UserInfo userInfo = UserInfoDaoManager.getUserByUid(ID);
                        if (userInfo == null) {
                            userInfo = new UserInfo();
                            userInfo.setUserId(ID);
                            UserInfoDaoManager.insertUser(userInfo);
                        }
                        if (!TextUtils.isEmpty(thirdinfo.getData().getAvatar())) {
                            userInfo.setIconPath(thirdinfo.getData().getAvatar());
                        }
                        int age = 25;
                        if (!TextUtils.isEmpty(thirdinfo.getData().getBirthday())) {
                            String[] birthdayArray = thirdinfo.getData().getBirthday().split("-");
                            int year = Integer.parseInt(birthdayArray[0]);
                            Calendar calendar = Calendar.getInstance();
                            int nowYear = calendar.get(Calendar.YEAR);
                            age = nowYear - year;
                            userInfo.setAge(age);
                            userInfo.setBirthday(thirdinfo.getData().getBirthday());
                        }
                        if (!TextUtils.isEmpty(thirdinfo.getData().getGender())) {
                            userInfo.setGender(thirdinfo.getData().getGender().equals("male") ? 0 : 1);
                        }
                        if (!TextUtils.isEmpty(thirdinfo.getData().getNikeName())) {
                            userInfo.setName(thirdinfo.getData().getNikeName());
                        }
                        userInfo.setWeight(thirdinfo.getData().getWeight());
                        userInfo.setHeight(thirdinfo.getData().getStature());
                        UserInfoDaoManager.updateUser(userInfo);
                        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, true);
                        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_AUTH_USERID, uid);
                        startActivity();
                        getActivity().finish();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }


    AlertDialog gpsDialog;

    private void ShowDialog(final String packageName, String MSG) {
        if (gpsDialog == null) {
            gpsDialog = new AlertDialog.Builder(getActivity(), R.style.appalertdialog)
                    .setMessage(MSG)
                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Utils.GoAppShop(packageName, getActivity());
                        }
                    })
                    .setNegativeButton(getString(R.string.cancel), null)
                    .create();
        }
        if (!gpsDialog.isShowing()) gpsDialog.show();
    }


}
